package com.bt.mes.common.core.history.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.bt.mes.common.bean.entity.HisXml;
import com.bt.mes.common.bean.entity.LoadHistoryConfig;
import com.bt.mes.common.core.context.AppContext;
import com.bt.mes.common.core.history.service.ISendHistoryService;
import com.bt.mes.common.core.rabbitmq.RabbitmqManager;
import com.bt.mes.common.util.MqOpe;
import com.bt.mes.common.util.TableConfigUtil;

@Scope("prototype")
@Component
public class SendHistoryService implements ISendHistoryService {
	@Resource
	private LoadHistoryConfig loadHistoryConfig;
	@Resource
	private TableConfigUtil tableConfigUtil;
	@Resource
	private RabbitmqManager rabbitmqManager;
	@Autowired
	private MqOpe mqOpe;
	public static final String RETURN_CODE_DEF_XML = "<rtn_code>0000000</rtn_code>";

	public boolean isTransactionSuccessed(String rtnMessage) {
		return (rtnMessage.indexOf(RETURN_CODE_DEF_XML) != -1);
	}

	// TODO:关于队列分组
	public String getHisQueueNameByTable(String tableName) {
		if (tableName.equals("RET_PRD_INFO")) {
			return loadHistoryConfig.getRetPrdSeqQueue();
		} else if (tableName.equals("SPC_RET_MFG_DATA")) {
			return loadHistoryConfig.getEdcQueue();
		} else {
			return loadHistoryConfig.getHistoryQueue();
		}
	}

	public void sendHistoryMessageToThreadAppContext(Object entity) {
		String tableName = entity.getClass().getSimpleName().toUpperCase();
		if (StringUtils.isEmpty(tableName)) {
			return;
		}
		if (hasToSendHis(tableName)) {
			String hisQueueName = getHisQueueNameByTable(tableName);
			if (!StringUtils.isEmpty(hisQueueName)) {

				List<HisXml> hisXmlList = AppContext.getCurrHisXmlList();
				if (hisXmlList == null) {
					hisXmlList = new ArrayList<HisXml>();
				}
				String xml = mqOpe.hisQueryReport(entity);
				hisXmlList.add(new HisXml(tableName, xml));
				AppContext.setCurrHisXmlList(hisXmlList);
			}
		}

	}

	public boolean hasToSendHis(String tableName) {
		return tableConfigUtil.checkSendHis(tableName);
	}

	public void sendHistoryMessageToRabbitMQ() {
		List<HisXml> hisXmlList = AppContext.getCurrHisXmlList();
		if (hisXmlList == null) {
			return;
		}
		for (HisXml hisXml : hisXmlList) {
			String tableName = hisXml.getTableName();
			String hisQueueName = getHisQueueNameByTable(tableName);
			rabbitmqManager.setMessage(hisQueueName, hisXml.getXml());
		}

	}

}
